import { Inject, Provide } from '@midwayjs/core';
import { makeHttpRequest } from '@midwayjs/core';
import * as bullmq from '@midwayjs/bullmq';

@Provide()
export class JyLoginProService {
  @Inject()
  bullmqFramework: bullmq.Framework;

  //将任务推入队列
  async pushTask(k: string) {
    const testQueue = this.bullmqFramework.getQueue('jyLoginPro');
    // 立即添加这个任务
    await testQueue?.addJobToQueue({
      k: k,
    });
    return 'success';
  }

  //login
  async login(k: string, ctx: any, account: any) {
    const page = await ctx.newPage();
    await page.setDefaultNavigationTimeout(60000); // 60秒
    await page.setDefaultTimeout(60000); // 其他操作的超时时间
    await page.setExtraHTTPHeaders({
      'Accept-Language': 'zh-CN,zh;q=0.9',
    });

    let phone = '';
    // eslint-disable-next-line eqeqeq
    if (account.phoneType == 1) {
      phone = '+1' + account.phoneNum;
    }
    if (account.phoneType == 0 || account.phoneType == 2) {
      phone = '+86' + account.phoneNum;
    }

    //查询商品信息
    const goodsInfo = (await this.getProductInfo(k)) as any;
    //time
    const time = new Date().getTime();

    await page.setUserAgent(
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
    );
    await page.setViewport({ width: 1366, height: 768 });
    await page.goto(
      'https://mlv-actx.editorjianying.com/lv_pc/login_proxy?platform=apple&login_id=38dfeeb1-cf24-4e78-bb8f-4f11e078e8fb&lng=zh-Hans&brand=null&country=null&enter_from=portrait&enter_channel=null&vip_type=null&is_preinstalled=false',
      {
        timeout: 60000,
      }
    );
    console.log(
      '打开页面',
      '-----',
      account.phoneNum,
      '-----',
      k,
      '-----',
      new Date().toLocaleString()
    );

    await this.wait(3000);
    await page
      .locator('#account_name_text_field')
      .setTimeout(30000)
      .fill(phone);

    await page.locator('#sign-in').setTimeout(3000).click();
    try {
      await page.locator('#continue-password').setTimeout(3000).click();
    } catch (error) {
      console.log('没有继续用密码登录');
    }
    await page
      .locator('#password_text_field')
      .setTimeout(10000)
      .fill(account.value);
    await page.locator('#sign-in').setTimeout(3000).click();
    await this.wait(9000);

    await page.locator('#stepEl');

    await this.wait(1000);
    let attempts = 0;
    let code = '';
    //是否继续循环
    let isContinue = true;

    while (isContinue) {
      const response = (await this.getCode(
        account.phoneNum,
        account.phoneNumId,
        account.phoneType,
        time,
        goodsInfo.data.data
      )) as any;

      if (
        response?.data.code === 1000 &&
        response?.data?.data &&
        response?.data?.data?.code
      ) {
        code = response.data.data.code;
        //停止循环
        isContinue = false;
      }

      // eslint-disable-next-line eqeqeq
      if (attempts++ == 15) {
        isContinue = false;
        //截图
        console.log('错误截图');
        await page.screenshot({
          path: `${account.phoneNum + '-' + new Date().toString()}.png`,
        });
        await this.stop(account.phoneNum);
        throw new Error('多次尝试后仍未获取到验证码');
      }
      console.log('等待验证码中，3秒后重试...');
      await this.wait(3000);
    }

    await this.wait(1000);
    const codeInput = await page.$$('.form-security-code-input');

    // 遍历并输入值
    for (let i = 0; i < codeInput.length; i++) {
      await codeInput[i].type(code[i] + '');
    }
    await this.wait(3000);
    //等待出现以信任浏览器
    await page.locator('.button-rounded-rectangle').click();

    await this.wait(2000);
    await page.locator('.overflow-text').click();

    // 显式等待登录成功的响应（阻塞主流程）
    const loginSuccessResponse = await page.waitForResponse(
      response =>
        response
          .url()
          .includes(
            'https://mlv-actx.editorjianying.com/lv_pc/login_status?code'
          ),
      { timeout: 60000 } // 超时时间
    );
    console.log(
      '成功登录',
      '-----',
      phone,
      '-----',
      k,
      '-----',
      new Date().toLocaleString()
    );
    await this.notify(k, loginSuccessResponse.url(), code, 2, account.phoneNum);
    //关闭网页
    await ctx.close();
  }

  //获取账号密码
  async getAccountPassword(k: string) {
    const url =
      'http://kukukuadmin.580dkw.com/api/open/coupe/comm/creatQuery?k=' +
      k +
      '&tag=qeznkbo';
    const result = await makeHttpRequest(url, {
      method: 'GET',
      dataType: 'json', // 返回的数据格式
    });
    return result;
  }

  // };
  async wait(time) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  }

  //成功后通知更新
  async notify(
    k: string,
    loginUrl: string,
    code: string,
    status = 2,
    phone: string
  ) {
    const url =
      'http://kukukuadmin.580dkw.com/api/open/coupe/comm/activeCdkeyComplete';
    const result = await makeHttpRequest(url, {
      data: {
        loginUrl: loginUrl,
        cdkey: k,
        code: code,
        status: status,
        phone: phone,
      },
      method: 'POST',
      dataType: 'json', // 返回的数据格式
      contentType: 'json',
    });
    return result;
  }

  //失败以后停用号码
  async stop(phone: number) {
    const url = 'http://kukukuadmin.580dkw.com/api/open/coupe/comm/stopPhone';
    const result = await makeHttpRequest(url, {
      data: {
        phoneNumber: phone,
        groupId: 3,
      },
      method: 'POST',
      dataType: 'json', // 返回的数据格式
      contentType: 'json',
    });
    console.log('失败了停用号码');
    return result;
  }

  //取卡接口
  async getCard(cdkey: string) {
    const url = 'http://kukukuadmin.580dkw.com/api/open/coupe/comm/jyGetCard';
    const result = await makeHttpRequest(url, {
      data: {
        cdkey,
      },
      method: 'POST',
      dataType: 'json', // 返回的数据格式
      contentType: 'json',
    });
    return result;
  }
  //查询商品信息
  async getProductInfo(cdkey: string) {
    const url =
      'http://kukukuadmin.580dkw.com/api/open/coupe/comm/jyGetGoodsInfo?cdkey=' +
      cdkey;
    const result = await makeHttpRequest(url, {
      method: 'GET',
      dataType: 'json', // 返回的数据格式
      contentType: 'json',
    });
    return result;
  }

  //获取验证码接口
  async getCode(
    phoneNum: string,
    phoneNumId: number,
    phoneType,
    time: number,
    goods: any
  ) {
    const url = 'http://kukukuadmin.580dkw.com/api/open/coupe/comm/jyGetCode';
    const result = await makeHttpRequest(url, {
      data: {
        phoneNum,
        phoneNumId,
        phoneType,
        time,
        goods,
      },
      method: 'POST',
      dataType: 'json', // 返回的数据格式
      contentType: 'json',
    });
    return result;
  }

  //失败后通知更新
  async failNotify(k: string, lockPhoneNum: string) {
    const url =
      'http://kukukuadmin.580dkw.com/api/open/coupe/comm/jyOperationFail';
    const result = await makeHttpRequest(url, {
      data: {
        cdkey: k,
        status: 3,
        lockPhoneNum,
      },
      method: 'POST',
      dataType: 'json', // 返回的数据格式
      contentType: 'json',
    });
    return result;
  }
}
